package com.linzm.leetcode.mid.tree.其他;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author zimingl
 * @Date 2023/3/17 0:02
 * @Description: 二叉搜索树的最小绝对差
 *
 * 树中节点的数目范围是 [2, 104]
 * 0 <= Node.val <= 105
 */
public class Demo24GetMinimumDifference530 {
    public int getMinimumDifference(TreeNode root) {
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<Integer> list = new ArrayList<>();
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
                list.add(node.val);
                size--;
            }
        }
        List<Integer> listSorted = list.stream().sorted().collect(Collectors.toList());
        int min = Integer.MAX_VALUE;
        for (int i = 1; i < listSorted.size(); i++) {
            min = Math.min(min, listSorted.get(i) - listSorted.get(i - 1));
        }
        return min;
    }
}
